<?php

namespace App\Http\Controllers\Api;

use App\Imports\BooksImport;
use App\Models\Book;
use App\Models\BookComment;
use App\Models\BookCommentGood;
use App\Models\BookHotSearchWord;
use App\Models\BookPublishInfo;
use App\Models\BookRecommendPositionRelation;
use App\Models\UserCart;
use App\Models\UserLikeCategory;
use App\Models\UserSearchWord;
use Illuminate\Http\Request;
use App\Common\ErrorCode;
use Maatwebsite\Excel\Facades\Excel;

class BooksController extends BaseController
{
    public function index(Request $request)
    {
        $category_id = intval($request->input('category_id'));
        $category_parent_id = intval($request->input('category_parent_id'));
        $page = intval($request->input('page',1));
        $per_page = intval($request->input('per_page',20));

        $builder = Book::query()->where('deleted',0)->where('on_sale',1);
        if(!empty($category_id))
        {
            $builder->where('category_id',$category_id);
        }

        if(!empty($category_parent_id))
        {
            $builder->where('category_parent_id',$category_parent_id);
        }

        $list = $builder->orderBy('total_read_num','desc')->paginate($per_page,['id','title','author','intro','total_read_num','douban_score','image','store'],'page',$page);

        $items = [];
        if(!empty($list->items()))
        {
            foreach ($list->items() as $item)
            {
                $item['intro'] = replace_intro($item['intro']);
                $item['image'] = config('app.qiniu_image_domain').DIRECTORY_SEPARATOR.$item['image'];
                $items[] = $item;
            }
        }

        $data = [
            '_meta' => [
                'total_count' => $list->total(),
                'page_count' => $list->lastPage(),
                'current_page' => $list->currentPage(),
                'per_page' => $list->perPage()
            ],
            "items" => $items
        ];

        return $this->res([
            'data' => $data
        ]);
    }

    public function getList(Request $request)
    {
        $type = intval($request->input('type')); //1=豆瓣高分 2=小编力荐 3=最新出版
        $page = intval($request->input('page',1));
        $per_page = intval($request->input('per_page',20));

        if(empty($type) || !in_array($type,[1,2,3]))
        {
            return $this->error(ErrorCode::PARAMS_NOT_VALID_CODE,ErrorCode::PARAMS_NOT_VALID_MESSAGE);
        }

        $ids_arr = BookRecommendPositionRelation::query()->where('book_recommend_position_id',$type)->pluck('book_id');
        //print_r($ids_arr);

        $builder = Book::query()->with(['category'])->where('deleted',0)->where('on_sale',1)->whereIn('id',$ids_arr);
        if($type == 1)
        {
            $builder = $builder->orderBy('douban_score','desc');
        }
        elseif($type == 2)
        {
            $builder = $builder->orderBy('total_read_num','desc');
        }
        else
        {
            $builder = $builder->orderBy('total_read_num','desc');
        }
        $books = $builder->paginate($per_page,['id','title','author','image','douban_score','category_id','total_read_num','intro','store'],'page',$page);

        $items = [];
        if(!empty($books))
        {
            foreach ($books as $v)
            {
                $items[] = [
                    'id' => $v['id'],
                    'title' => $v['title'],
                    'store' => $v['store'],
                    'intro' => replace_intro($v['intro']),
                    'image' => config('app.qiniu_image_domain').DIRECTORY_SEPARATOR.$v['image'],
                    'author' => $v['author'],
                    'douban_score' => $v['douban_score'],
                    'category_title' => $v->category->title
                ];
            }
        }

        $data = [
            '_meta' => [
                'total_count' => $books->total(),
                'page_count' => $books->lastPage(),
                'current_page' => $books->currentPage(),
                'per_page' => $books->perPage()
            ],
            "items" => $items
        ];

        return $this->res([
            'data' => $data
        ]);
    }

    public function show(Book $book, Request $request)
    {
        //判断是否已经加入书架
        $user_id = intval($request->input('user_id'));
        if(empty($user_id))
        {
            return $this->error(ErrorCode::PARAMS_NOT_VALID_CODE,ErrorCode::PARAMS_NOT_VALID_MESSAGE);
        }

        $publish_info = BookPublishInfo::query()->where('book_id',$book->id)->first();

        $cart = UserCart::query()->where(['user_id'=>$user_id,'book_id'=>$book->id])->first();
        $is_cart = !empty($cart)?1:0;
        $info = [
            'id' => $book->id,
            'title' => $book->title,
            'store' => $book->store,
            'image' => config('app.qiniu_image_domain').DIRECTORY_SEPARATOR.$book->image,
            'author' => $book->author,
            'total_read_num' => $book->system_user_read_num+$book->real_user_read_num,
            'douban_score' => $book->douban_score,
            'intro' => replace_intro($book->intro),
            'catalog' => $book->catalog,
            'comment_num' => BookComment::query()->where('book_id',$book->id)->where('status',2)->where('deleted',0)->count(),
            'is_cart' => $is_cart,
            'publish_info' => $publish_info
        ];

        //加喜欢的分类权重
        UserLikeCategory::addUserLikeCategoryScore($this->user_id,$book->category_id,UserLikeCategory::VIEW_WEIGHT);

        return $this->res([
            'data' => $info
        ]);
    }

    public function comments(Book $book, Request $request)
    {
        $page = intval($request->input('page',1));
        $per_page = intval($request->input('per_page',20));

        $total_count = BookComment::query()->where('book_id',$book->id)->where('status',2)->where('deleted',0)->count();

        $page = max(1,$page);
        $offset = ($page - 1)*$per_page;
        $page_count = ceil($total_count/$per_page);

        $comments = BookComment::query()->with(['user'])->where('book_id',$book->id)->where('status',2)->where('deleted',0)->orderBy('id','desc')->offset($offset)->limit($per_page)->get();

        $items = [];
        if(!empty($comments))
        {
            foreach ($comments as $v)
            {
                $is_good = 0;
                if(BookCommentGood::query()->where('user_id',$this->user_id)->where('comment_id',$v['id'])->count() > 0)
                {
                    $is_good = 1;
                }

                $items[] = [
                    'id' => $v['id'],
                    'good_num' => $v['good_num'],
                    'content' => $v['content'],
                    'user_id' => $v['user_id'],
                    'rate' => $v['rate'],
                    'wechat_nickname' => $v['user']['wechat_nickname'],
                    'wechat_avatar' => $v['user']['wechat_avatar'],
                    'is_good' => $is_good
                ];
            }
        }

        return $this->res([
            'data' => [
                '_meta' => [
                    'total_count' => $total_count,
                    'page_count' => $page_count,
                    'current_page' => $page,
                    'per_page' => $per_page
                ],
                'items' => $items
            ]
        ]);
    }

    public function storeGood(Request $request)
    {
        $user_id = $request->input('user_id');
        $comment_id = $request->input('comment_id');

        if(empty($user_id) || empty($comment_id))
        {
            return $this->error(ErrorCode::PARAMS_NOT_VALID_CODE,ErrorCode::PARAMS_NOT_VALID_MESSAGE);
        }

        $good = BookCommentGood::query()->where(['user_id'=>$user_id,'comment_id'=>$comment_id])->first();
        if(!empty($good))
        {
            return $this->error(10000,'已点赞');
        }

        $comment_good = new BookCommentGood([
            'user_id' => $user_id,
            'comment_id' => $comment_id
        ]);
        $comment_good->save();

        BookComment::query()->where('id',$comment_id)->increment('good_num');
        return $this->success();
    }

    public function destroyGood(Request $request)
    {
        $user_id = $request->input('user_id');
        $comment_id = $request->input('comment_id');

        if(empty($user_id) || empty($comment_id))
        {
            return $this->error(ErrorCode::PARAMS_NOT_VALID_CODE,ErrorCode::PARAMS_NOT_VALID_MESSAGE);
        }

        $good = BookCommentGood::query()->where(['user_id'=>$user_id,'comment_id'=>$comment_id])->first();
        if(empty($good))
        {
            return $this->error(10000,'尚未点赞');
        }

        BookCommentGood::destroy($good->id);

        BookComment::query()->where('id',$comment_id)->decrement('good_num');
        return $this->success();
    }

    public function searchPage(Request $request)
    {
        $user_id = intval($request->input('user_id'));
        //我的历史搜索
        $histroys = UserSearchWord::query()->select('word')->where('user_id',$user_id)->orderBy('updated_at','desc')->limit(15)->get();

        //热门搜索
        $hots = BookHotSearchWord::query()->select('word')->orderBy('sort','asc')->limit(8)->get();

        return $this->success([
            'histroys' => $histroys,
            'hots' => $hots,
        ]);
    }

    public function search(Request $request)
    {
        $keyword = $request->input('keyword');
        $user_id = intval($request->input('user_id'));

        // 创建一个查询构造器
        $builder = Book::query()->select(['id','title','author','image','intro','total_read_num','douban_score','review_count','store'])->where('on_sale', 1)->where('deleted',0);
        if(!empty($keyword))
        {
            $like = '%'.$keyword.'%';

            $builder->where(function ($query) use ($like) {
                $query->where('title', 'like', $like)
                    ->orWhere('author', 'like', $like);
            });

            if(!empty($user_id))
            {
                $row = UserSearchWord::query()->where('user_id',$user_id)->where('word',$keyword)->first();
                if(empty($row))
                {
                    //添加搜索记录
                    UserSearchWord::query()->insert([
                        'user_id' => $user_id,
                        'word' => $keyword,
                        'updated_at' => time()
                    ]);
                }
                else
                {
                    UserSearchWord::query()->where('id',$row->id)->update([
                        'updated_at' => time()
                    ]);
                }

            }
        }
        $books = $builder->get();

        //var_dump($books);die;
        $items = [];
        if(!empty($books))
        {
            foreach ($books as $v)
            {
                $score = 0;
                if($v['review_count'] > 5)
                {
                    $score += 0.6;
                }

                if($v['douban_score'] > 0)
                {
                    $score += 1;
                }

                if($v['total_read_num'] > 50)
                {
                    $score += 0.3;
                }
                $items[] = [
                    'id' => $v['id'],
                    'title' => $v['title'],
                    'store' => $v['store'],
                    'intro' => replace_intro($v['intro']),
                    'image' => config('app.qiniu_image_domain').DIRECTORY_SEPARATOR.$v['image'],
                    'author' => $v['author'],
                    'score' => $score
                ];
            }
        }

        $items = array_sort($items, function ($user) {
            return $user['score'];
        });

        $items = array_reverse($items);
        
        $data = [
            "items" => $items
        ];

        return $this->res([
            'data' => $data
        ]);
    }

    public function import(Request $request, BooksImport $booksImport)
    {
        Excel::import($booksImport, $request->file('excel'), $request->input('category_id'));
        return $this->success([],'ok');
    }
}
